<?php

namespace App\Http\Controllers;

use App\Exceptions\AppException;
use App\Exceptions\AuthException;
use App\Http\Controllers\Controller;
use App\Libs\Company\SheetTemplateHandler\Manager;
use App\Models\AggregateFixReport;
use App\Models\AggregateReport;
use App\Services\AggregateReportService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AggregateReportController extends Controller
{
    public function list(Request $request)
    {
        $request->validate([
            'name' => 'nullable|string|max:50',
            'type' => 'nullable|in:1,2',
            'frequency' => 'nullable|in:monthly,once',
            'page' => 'nullable|integer|min:1',
            'per_page' => 'nullable|integer',
        ]);

        if (!Auth::user()->hasPermissionTo('aggregate-report')) {
            throw new AuthException();
        }
        $query = AggregateReport::with(['sheetTemplate'])->select(['id', 'sheet_template_id', 'frequency', 'year', 'key', 'updated_at']);
        if ($request->name) {
            $query->whereHas('sheetTemplate', function ($q) use ($request) {
                $q->where('name', 'like', "%{$request->name}%");
            });
        }
        if ($request->frequency) {
            $query->where('frequency', $request->frequency);
        }
        $res = $query->orderBy('updated_at', 'desc')->paginate($request->per_page);
        return responder()->success($res);
    }

    public function show(Request $request)
    {
        $request->validate([
            'id' => 'required|integer|exists:aggregate_reports,id,deleted_at,NULL',
        ]);

        if (!Auth::user()->hasPermissionTo('aggregate-report')) {
            throw new AuthException();
        }
        $model = AggregateReport::find($request->id);
        return responder()->success($model);
    }

    public function export(Request $request)
    {
        $request->validate([
            'id' => 'required|integer|exists:aggregate_reports,id,deleted_at,NULL',
        ]);

        if (!Auth::user()->hasPermissionTo('aggregate-report')) {
            throw new AuthException();
        }
        $model = AggregateReport::find($request->id);
        Manager::export($model->data, $model->data['sheets']['sheet-01']['cellData']['0']['0']['p']['body']['dataStream'] ?? $model->data['sheets']['sheet-01']['cellData']['0']['0']['v']);
        exit;
    }

    public function fix(Request $request)
    {
        $request->validate([
            'id' => 'required|integer|exists:aggregate_reports,id,deleted_at,NULL',
        ]);

        if (!Auth::user()->hasPermissionTo('aggregate-report')) {
            throw new AuthException();
        }
        $model = AggregateReport::find($request->id);
        if (AggregateReportService::isUsed($model)) {
            throw new AppException('该报告已被使用，无法上报');
        }
        // 只有 西藏旅游发展主要指标统计表 可上报
        if ($model->sheet_template_id != 221) {
            throw new AppException('只有 西藏旅游发展主要指标统计表 可上报');
        }

        $fixModel = AggregateFixReport::where([
            'sheet_template_id' => $model->sheet_template_id,
            'frequency' => $model->frequency,
            'year' => $model->year,
            'key' => $model->key,
        ])
            ->firstOrNew();
        if ($fixModel->id) {
            throw new AppException('该报告已上报，无法再次上报');
        }
        $fixModel->fill($model->toArray());
        $fixModel->operator_id = Auth::user()->id;
        $fixModel->save();
        return responder()->success();
    }
}
